<template>
  <div class="descendant-initial-container">
    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="danger" @click="handleSave">
          <el-icon><Document /></el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="danger" @click="handleUndo">
          <el-icon><RefreshLeft /></el-icon>
          <span>撤销</span>
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-icon class="toolbar-icon"><Setting /></el-icon>
        <el-icon class="toolbar-icon"><Printer /></el-icon>
      </div>
    </div>

    <!-- 信息显示区域 -->
    <div class="info-section">
      <div class="info-item">
        <span class="info-label">期初日期：</span>
        <span class="info-value">{{ initialDate }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">单据号：</span>
        <el-input 
          v-model="documentNumber" 
          placeholder="---" 
          class="info-input"
          disabled
        />
      </div>
      <div class="info-item">
        <span class="info-label">流水号：</span>
        <el-input 
          v-model="serialNumber" 
          placeholder="---" 
          class="info-input"
          disabled
        />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="sequence" label="序号" width="80" align="center" />
        <el-table-column prop="earTag" label="*耳号" align="center">
          <template #default="{ row }">
            <el-select
              v-model="row.earTag"
              placeholder="请选择耳号"
              size="small"
              clearable
              filterable
              :loading="loadingEarTags"
              style="width: 100%"
              @change="(value: string | null) => handleEarTagSelect(value, row)"
            >
              <el-option
                v-for="option in earTagOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="barn" label="*栋舍" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.barn"
              placeholder="请输入栋舍"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stage" label="*阶段" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.stage"
              placeholder="请输入阶段"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" align="center">
          <template #default="{ row }">
            <el-select
              v-model="row.gender"
              placeholder="请选择性别"
              size="small"
              clearable
            >
              <el-option label="公" :value="1" />
              <el-option label="母" :value="2" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="defaultCount" label="默认不能修改只数" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.defaultCount"
              size="small"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量(公斤)" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.weight"
              placeholder="请输入重量"
              size="small"
              type="number"
              step="0.01"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部汇总和操作 -->
    <div class="footer-section">
      <div class="summary">
        <span class="summary-label">合计：</span>
        <span class="summary-value">{{ totalWeight.toFixed(2) }}</span>
      </div>
      
      <div class="row-actions">
        <el-button type="danger" plain @click="handleAddRow">
          <el-icon><Plus /></el-icon>
          <span>增行</span>
        </el-button>
        <el-button type="danger" plain @click="handleDeleteRow">
          <el-icon><Minus /></el-icon>
          <span>删行</span>
        </el-button>
      </div>

      <div class="remarks">
        <span class="remarks-label">备注：</span>
        <el-input
          v-model="remarks"
          placeholder="请输入备注信息"
          class="remarks-input"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated } from 'vue'
import { Plus, Document, RefreshLeft, Delete, Setting, Printer, Minus } from '@element-plus/icons-vue'
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import router from '@/router'

// 基本信息
const initialDate = ref('2020-10-20')
const documentNumber = ref('')
const serialNumber = ref('')
const remarks = ref('')

// 耳号选项列表
const earTagOptions = ref<Array<{value: string, label: string}>>([])
const loadingEarTags = ref(false)

// 表格数据
const tableData = ref([
  {
    sequence: 1,
    earTag: '',
    barn: '',
    stage: '',
    gender: '',
    defaultCount: '1',
    weight: ''
  }
])

// 计算总重量
const totalWeight = computed(() => {
  return tableData.value.reduce((sum, row) => {
    const weight = parseFloat(row.weight) || 0
    return sum + weight
  }, 0)
})

// 操作处理
const handleAdd = () => {
  console.log('新增')
}

const handleSave = async () => {
  try {
    // 获取单据号（如果为空将使用雪花ID生成）
    const currentDocumentNumber = documentNumber.value || ''
    
    // 获取羊只ID列表（从耳号字段获取）
    const sheepIds: number[] = []
    const initialGenders: number[] = []
    
    tableData.value.forEach(row => {
      if (row.earTag) {
        const sheepId = parseInt(row.earTag)
        if (!isNaN(sheepId)) {
          sheepIds.push(sheepId)
          
          // 获取性别值：后裔通过下拉框的gender字段获取
          const genderValue = parseInt(row.gender) || 0
          initialGenders.push(genderValue)
        }
      }
    })
    
    // 构建请求数据
    const payload = {
      DocumentNumber: currentDocumentNumber,
      InitialGenders: initialGenders,
      Note: remarks.value,
      SheepIds: sheepIds
    }
    
    console.log('保存请求数据:', payload)
    
    // 发送POST请求
    const response = await Writes.post('/Management/CreateInitialformBatch', payload)
    console.log('保存响应:', response.data)
    
    if (response.data && response.data.code === 100) {
      ElMessage.success('保存成功')
      router.push('/descendant-initial-list')
      // 如果返回了新的单据号，更新到界面
      if (response.data.data && response.data.data.DocumentNumber) {
        documentNumber.value = response.data.data.DocumentNumber
      }
    } else {
      ElMessage.error(response.data?.Message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请检查网络连接')
  }
}

const handleUndo = () => {
  console.log('撤销')
}

const handleDelete = () => {
  console.log('删除')
}

const handleAddRow = () => {
  const newRow = {
    sequence: tableData.value.length + 1,
    earTag: '',
    barn: '',
    stage: '',
    gender: '',
    defaultCount: '1',
    weight: ''
  }
  tableData.value.push(newRow)
}

const handleDeleteRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
    // 重新编号
    tableData.value.forEach((row, index) => {
      row.sequence = index + 1
    })
  } else {
    // 如果只有一行，则清空数据
    tableData.value[0] = {
      sequence: 1,
      earTag: '',
      barn: '',
      stage: '',
      gender: '',
      defaultCount: '1',
      weight: ''
    }
  }
}

// 根据耳号查询后裔详细信息并反填
const fetchDescendantInfo = async (descendantId: number, row: any) => {
  try {
    console.log('查询后裔信息，ID:', descendantId)
    const response = await Reads.get(`/Management/GetDescendantFileById`,{
      params: {
        DescendantId: descendantId
      }
    })
    
    if (response.data && response.data.code === 400) {
      const info = response.data.data
      if (info) {
        // 反填数据到当前行 - 根据实际返回的字段结构
        row.barn = info.placeOfBirth?.toString() || ''  // 出生地作为羊舍
        row.stage = info.geneRank?.toString() || ''     // 基因等级作为阶段
        row.gender = info.gender || '' // 性别字段 (1:公, 2:母)
        row.weight = info.birthWeight?.toString() || '' // 出生体重作为体重
        console.log('后裔信息反填成功:', info)
      }
    } else {
      console.error('查询后裔信息失败:', response.data)
    }
  } catch (error) {
    console.error('查询后裔信息失败:', error)
  }
}

// 处理耳号选择事件
const handleEarTagSelect = async (value: string | null, row: any) => {
  // value为null或空字符串时表示取消选择
  const isSelected = !!value
  const descendantId = value ? parseInt(value) : (row.earTag ? parseInt(row.earTag) : 0)
  
  if (descendantId === 0) return
  
  // 如果选择了耳号，查询详细信息并反填
  if (value) {
    await fetchDescendantInfo(descendantId, row)
  }
  
  try {
    const payload = {
      DescendantId: descendantId,
      Initialstate: isSelected
    }
    
    console.log('发送后裔状态数据:', payload)
    const response = await Writes.put('/Management/UpdateDescendantInitialstate', payload)
    console.log('更新响应:', response.data)
    if (response.data && response.data.code === 300) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.error('更新失败')
    }
    console.log('后裔状态更新响应:', response.data)
  } catch (error) {
    console.error('更新后裔状态失败:', error)
  }
}

// 获取耳号列表
const fetchEarTagOptions = async () => {
  loadingEarTags.value = true
  try {
    // 尝试从现有牲畜数据中获取耳号列表
    const response = await Reads.get('/Management/GetDescendantFileMenu')
    
    if (response.data && response.data.code === 400) {
      console.log('响应数据:', response.data)
      const data = response.data.data || []
      // 直接使用返回的数据，它已经包含了value和label字段
      earTagOptions.value = data
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
    // 如果获取失败，使用默认的空列表
    earTagOptions.value = []
  } finally {
    loadingEarTags.value = false
  }
}

// 生成单据号和流水号
const generateDocumentNumbers = () => {
  const now = new Date()
  const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '') // YYYYMMDD格式
  const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '') // HHMMSS格式
  
  // 单据号格式：HXQ+日期+时间，如 HXQ20241225143000
  documentNumber.value = `HXQ${dateStr}${timeStr}`
  
  // 流水号格式：当前时间戳后6位，如 143000
  serialNumber.value = `${dateStr.slice(-6)}${timeStr}`
}

// 组件挂载时获取耳号列表
onMounted(() => {
  generateDocumentNumbers()
  fetchEarTagOptions()
})

// 页面刷新时重新生成编号
onActivated(() => {
  generateDocumentNumbers()
})
</script>

<style scoped>
.descendant-initial-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 15px;
}

.toolbar-icon {
  font-size: 18px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.toolbar-icon:hover {
  color: #409eff;
}

.info-section {
  display: flex;
  gap: 30px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.info-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.info-input {
  width: 120px;
}

.table-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.footer-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.summary-label {
  color: #606266;
  font-size: 14px;
  margin-right: 10px;
}

.summary-value {
  color: #303133;
  font-size: 14px;
  font-weight: 600;
  min-width: 100px;
  text-align: right;
}

.row-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.remarks {
  display: flex;
  align-items: center;
  gap: 10px;
}

.remarks-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.remarks-input {
  flex: 1;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-button--danger.is-plain) {
  background-color: transparent;
  border-color: #f56c6c;
  color: #f56c6c;
}

:deep(.el-button--danger.is-plain:hover) {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

/* 表格样式 */
:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600 !important;
}

:deep(.el-table td) {
  padding: 10px 0 !important;
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  border: none !important;
  padding: 0 !important;
}

:deep(.el-input__inner:focus) {
  border: 1px solid #409eff !important;
  border-radius: 4px;
  padding: 0 8px !important;
}
</style>

